package br.com.projeto.model.persistencia;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

public class DAO<T> {

	private Class<T> entityClass = null;

	public DAO(Class<T> enityClass) {
		this.entityClass = enityClass;
	}

	@SuppressWarnings("unchecked")
	public List<T> listar() {
		EntityManager context = EntityManagerHelper.getEntityManager();
		try {
			return context.createQuery(
					String.format("select u from %s u", this.entityClass
							.getSimpleName())).getResultList();
		} finally {
			context.close();
		}
	}

	public void inserir(T entidade) {

		EntityManager em = EntityManagerHelper.getEntityManager();
		EntityTransaction t = em.getTransaction();
		try {

			t.begin();
			em.persist(entidade);
			t.commit();

		} catch (Exception e) {

			e.printStackTrace();
			if (t.isActive())
				t.rollback();

		} finally {

			em.close();

		}

	}

/*	public void atualizar(T entidade) {

		EntityManager em = EntityManagerHelper.getEntityManager();
		EntityTransaction t = em.getTransaction();
		try {

			t.begin();
			em.merge(entidade);
			t.commit();

		} catch (Exception e) {

			e.printStackTrace();
			if (t.isActive())
				t.rollback();

		} finally {

			em.close();

		}

	}*/

	public void remover(Object id) {

		EntityManager em = EntityManagerHelper.getEntityManager();
		EntityTransaction t = em.getTransaction();
		try {

			t.begin();
			T e = (T) em.find(entityClass, id);
			em.remove(e);
			t.commit();

		} catch (Exception e) {

			e.printStackTrace();
			if (t.isActive())
				t.rollback();

		} finally {

			em.close();

		}

	}

	public T localizar(Object id) {

		EntityManager em = EntityManagerHelper.getEntityManager();
		try {
			return (T) em.find(entityClass, id);
		} catch (Exception e) {
			System.out.println(e.getMessage());
			return null;
		} finally {
			em.close();
		}
	}
	
	
	protected String buildJoinedSingleQuery(String... relations) {
		StringBuilder builder = new StringBuilder();
		
		builder.append(String.format("SELECT DISTINCT o FROM %s o ", this.entityClass.getSimpleName()));
		
		for (String relation : relations) {
			builder.append(String.format("LEFT JOIN FETCH o.%s ", relation));
		}
		
		builder.append("WHERE o.id = :id");
		
		return builder.toString();
	}

}
